package com.kx.kxpicture.manager.upload;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import com.kx.kxpicture.config.CosClientConfig;
import com.kx.kxpicture.exception.BusinessException;
import com.kx.kxpicture.exception.ErrorCode;
import com.kx.kxpicture.manager.CosManager;
import com.kx.kxpicture.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * 图片上传模板方法
 *
 * @author kuangxin
 * date 2025/9/3
 */
@Slf4j
public abstract class PictureUploadTemplate {


    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 校验图片
     * @param inputSource
     */
    protected abstract void validPicture(Object inputSource);
    /**
     * 获取图片名称
     * @param inputSource
     * @return
     */
    protected abstract String getOriginFilename(Object inputSource);

    /**
     * 保存临时文件
     * @param inputSource
     * @param file
     * @throws Exception
     */
    protected abstract void processFile(Object inputSource, File file) throws Exception;



    /**
     * 上传图片
     * @param inputSource
     * @param uploadPrefix 图片相对路径
     */
    public final UploadPictureResult uploadPicture(Object inputSource, String uploadPrefix){
        validPicture(inputSource);
        String uuid = RandomUtil.randomString(16);
        String originalFilename = getOriginFilename(inputSource);
        //上传的文件名=日期+uuid+文件名
        String safeDate = DateUtil.format(new Date(), "yyyy-MM-dd_HH-mm-ss");
        String uploadFileName = String.format("%s_%s.%s", safeDate,uuid, FileUtil.getSuffix(originalFilename));
        //上传路径
        String uploadPath = String.format("/%s/%s",uploadPrefix,uploadFileName);
        File file=null;
        try {
            //图片保存
            file = File.createTempFile(uploadPath,null);
            processFile(inputSource,file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            //得到原图信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            //得到压缩处理后的图片信息
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if (ObjUtil.isNotEmpty(objectList)){
                //不为空直接封装到数据库并返回
                CIObject ciObject = objectList.get(0);
                CIObject thumbnailCiObject = ciObject;
                if (objectList.size()>1){
                    //取出缩略图信息
                     thumbnailCiObject = objectList.get(1);
                }
                return buildPictureResult(originalFilename,ciObject,thumbnailCiObject);
            }
            //否则返回原图信息
            UploadPictureResult uploadPictureResult = buildPictureResult(imageInfo, uploadPath, originalFilename, file);
            return uploadPictureResult;
        }catch (Exception e){
            log.error("图片上传失败{}",e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图片上传失败");
        }finally {
            deleteFile(file);
        }
    }

    private UploadPictureResult buildPictureResult(String originFilename, CIObject compressedCiObject, CIObject thumbnailCiObject) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());

        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
        return uploadPictureResult;
    }

    private UploadPictureResult buildPictureResult(ImageInfo imageInfo, String uploadPath, String originalFilename, File file) {
        String format = imageInfo.getFormat();
        int width = imageInfo.getWidth();
        int height = imageInfo.getHeight();
        double scale = NumberUtil.round(width*1.0/height,2).doubleValue();
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosClientConfig.getHost()+ uploadPath);
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicWidth(width);
        uploadPictureResult.setPicHeight(height);
        uploadPictureResult.setPicScale(scale);
        uploadPictureResult.setPicFormat(format);
        return uploadPictureResult;
    }


    /**
     * 删除临时文件
     * @param file
     */
    private final void deleteFile(File file) {
        if (file==null){
            return;
        }
        boolean delete = file.delete();
        if (!delete){
            log.error("文件删除错误，filepath={}", file.getAbsolutePath());
        }
    }
}
